package com.itlong.cloud.operate.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.itlong.cloud.POJO.DTO.operate.OperateSceneGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateSceneSaveDTO;
import com.itlong.cloud.POJO.PO.OperateScenePO;
import com.itlong.cloud.POJO.PO.OperateSceneUserTypePO;
import com.itlong.cloud.POJO.VO.operate.OperateSceneVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.OperateConstant;
import com.itlong.cloud.operate.dao.IOperateSceneDao;
import com.itlong.cloud.operate.service.IOperateProjectService;
import com.itlong.cloud.operate.service.IOperateSceneService;
import com.itlong.cloud.operate.service.IOperateSceneUserTypeService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.string.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 * 场景管理接口实现
 * </desc>
 *
 * @createDate 2021-03-25
 */
@Service
public class OperateSceneServiceImpl implements IOperateSceneService {

    @Autowired
    private IOperateSceneDao iOperateSceneDao;

    @Autowired
    IOperateSceneUserTypeService iOperateSceneUserTypeService;

    @Autowired
    IOperateProjectService iOperateProjectService;

    /**
     * <desc>
     * 添加场景
     * <desc/>
     *
     * @param saveDTO 添加场景
     * @return
     * @author zhouchun
     * @createDate 2021-03-25
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer saveScene(OperateSceneSaveDTO saveDTO) throws Exception {
        Date createTime = new Date();
        //人员类型的id列表
        List<String> userTypeId = new ArrayList();
        String[] list = saveDTO.getUserType().split(",");
        for (String name : list) {
            String id = LogicIdUtil.bussinessId();
            userTypeId.add(id);
            OperateSceneUserTypePO model = new OperateSceneUserTypePO();
            model.setUserTypeId(id);
            model.setSceneId(saveDTO.getSceneId());
            model.setName(name);
            model.setSpecial(0);
            if (OperateConstant.OPERATE_SCENE_USER_TYPE_SPECIAL_NAME.equals(name)) {
                model.setSpecial(1);
            }
            model.setStatus(1);
            model.setCreateUserId(saveDTO.getCreateUserId());
            model.setOperateUserId(saveDTO.getOperateUserId());
            model.setCreateTime(createTime);
            model.setUpdateTime(createTime);
            Integer result = iOperateSceneUserTypeService.save(model);
            if (result <= 0) {
                throw new DataAccessException("【创建场景失败】");
            }
        }
        OperateScenePO m = new OperateScenePO();
        BeanUtils.copyProperties(saveDTO, m);
        m.setUserTypeId(StringUtils.join(userTypeId, ","));
        m.setStatus(1);
        m.setCreateTime(createTime);
        m.setUpdateTime(createTime);
        Map<String, Object> params = SqlUtil.durableData(m, PlatformConstants.TABLE_SAVE);
        Integer res = iOperateSceneDao.save(params);
        if (res <= 0) {
            throw new DataAccessException("【创建场景失败】");
        }
        return res;
    }

    /**
     * <desc>
     * 修改场景
     * <desc/>
     *
     * @param saveDTO 修改场景
     * @return
     * @author zhouchun
     * @createDate 2021-03-25
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer updateScene(OperateSceneSaveDTO saveDTO) throws Exception {
        Date createTime = new Date();
        //编辑时传递[{"userTypeId":"","name":""}]
        List<String> userTypeIdList = new ArrayList();
        JSONArray array = JSONObject.parseArray(saveDTO.getUserType());
        for (int i = 0; i < array.size(); i++) {
            JSONObject item = array.getJSONObject(i);
            String userTypeId = StringUtil.saveNum(item.getString("userTypeId"));//需要防sql注入
            String name = item.getString("name");
            //新增
            if (userTypeId.equals("")) {
                String id = LogicIdUtil.bussinessId();
                userTypeIdList.add(id);
                OperateSceneUserTypePO model = new OperateSceneUserTypePO();
                model.setUserTypeId(id);
                model.setSceneId(saveDTO.getSceneId());
                model.setName(name);
                model.setSpecial(0);
                if (OperateConstant.OPERATE_SCENE_USER_TYPE_SPECIAL_NAME.equals(name)) {
                    model.setSpecial(1);
                }
                model.setStatus(1);
                model.setCreateUserId(saveDTO.getCreateUserId());
                model.setOperateUserId(saveDTO.getOperateUserId());
                model.setCreateTime(createTime);
                model.setUpdateTime(createTime);
                Integer result = iOperateSceneUserTypeService.save(model);
                if (result <= 0) {
                    throw new DataAccessException("【添加人员类型失败】");
                }
            } else {
                OperateSceneUserTypePO model = iOperateSceneUserTypeService.getOneByUserTypeId(userTypeId);
                model.setName(name);
                model.setSpecial(0);
                if (OperateConstant.OPERATE_SCENE_USER_TYPE_SPECIAL_NAME.equals(name)) {
                    model.setSpecial(1);
                }
                model.setOperateUserId(saveDTO.getOperateUserId());
                model.setUpdateTime(createTime);
                iOperateSceneUserTypeService.update(model);
                userTypeIdList.add(userTypeId);
            }
        }
        String userTypeIds = StringUtils.join(userTypeIdList, ",");
        //删除
        iOperateSceneUserTypeService.deleteByUserTypeIdsNotIn(saveDTO.getSceneId(), userTypeIds);
        //
        OperateScenePO m = new OperateScenePO();
        BeanUtils.copyProperties(saveDTO, m);
        m.setUserTypeId(userTypeIds);
        m.setUpdateTime(createTime);
        Integer res = iOperateSceneDao.update(m);
        if (res <= 0) {
            throw new DataAccessException("【修改场景失败】");
        }
        return res;
    }

    @Override
    public Integer getCountByName(String name) {
        return iOperateSceneDao.getCountByName(name);
    }

    @Override
    public Integer getExcludeCountByName(String name, String sceneKey) {
        return iOperateSceneDao.getExcludeCountByName(name, sceneKey);
    }

    /**
     * <desc>
     * 分页查询场景信息
     * <desc/>
     *
     * @param pageDTO 分页查询场景信息DTO
     * @return
     * @author zhouchun
     * @createDate 2021-03-26
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateSceneVO> getPage(OperateSceneGetPageDTO pageDTO) throws Exception {
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(pageDTO);
        PageHelper.startPage(Integer.parseInt(pageDTO.getCurrentPage()), Integer.parseInt(pageDTO.getPageSize()));
        com.github.pagehelper.Page<OperateSceneVO> page = iOperateSceneDao.getSimplePage(params);
        Page<OperateSceneVO> returnPage = new Page<>(pageDTO.getCurrentPage(), pageDTO.getPageSize());
        //根据列表里面的人员类型id查出记录
        List<OperateSceneVO> list = page.getResult();
        List<String> all = new ArrayList<>();
        for (OperateSceneVO item : list) {
            all.addAll(StringUtil.string2List(item.getUserTypeId()));
        }
        //一次性查数据库
        List<OperateSceneUserTypePO> allList = new ArrayList<>();
        if (all.size() > 0) {
            allList = iOperateSceneUserTypeService.getListByIds(StringUtils.join(all, ","));
        }
        for (OperateSceneUserTypePO v : allList) {
            for (OperateSceneVO vv : list) {
                if (vv.getUserTypeId().indexOf(v.getUserTypeId()) >= 0) {
                    if (vv.getUserTypeList() == null) {
                        vv.setUserTypeList(new ArrayList<>());
                    }
                    vv.getUserTypeList().add(v);
                }
            }
        }
        returnPage.setRows(list, (int) page.getTotal());
        return returnPage;
    }

    @Override
    public Integer userTypeIdCanDelete(String userTypeId) {
        OperateSceneUserTypePO m = iOperateSceneUserTypeService.getOneByUserTypeId(userTypeId);
        if (m == null || m.getSpecial() == 0) {
            return 1;
        }
        return 0;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer delete(OperateScenePO m) {
        if (isRef(m.getSceneId())) {
            return 1;
        }
        //删除数据就是修改状态
        m.setStatus(0);
        m.setUpdateTime(new Date());
        iOperateSceneDao.update(m);
        return 0;
    }

    /**
     * 场景是否被引用
     *
     * @param sceneId
     * @return
     */
    public boolean isRef(String sceneId) {
        return iOperateProjectService.getCountBySceneId(sceneId) > 0;
    }

    @Override
    public OperateScenePO getOneBySceneId(String sceneId) {
        return iOperateSceneDao.getOneBySceneId(sceneId);
    }

}